package com.jopen.wia.cheese;

import java.text.NumberFormat;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

public class Index extends CheesePage {
	private ShoppingCartPanel shoppingCart;
	private Link checkout;
	private WebMarkupContainer cartContainer;
	
	public Index() {
		PageableListView cheeses = new PageableListView("cheeses", getCheeses(), 5) {
			protected void populateItem(ListItem item) {
				Cheese cheese = (Cheese) item.getModelObject();
				item.add(new Label("name", cheese.getName()));
				item.add(new Label("description", cheese.getDescription()));
				item.add(new Label("price", "$" + cheese.getPrice()));
				
//				item.add(new Link("add", item.getModel()) {
//					public void onClick() {
//						Cheese selected = (Cheese) getModelObject();
//						getCart().add(selected);
//					}
//				});
				item.add(new AjaxFallbackLink("add", item.getModel()) {
					public void onClick(AjaxRequestTarget target) {
						Cheese selected = (Cheese) getModelObject();
						getCart().add(selected);
						if (target != null) {
							target.addComponent(cartContainer);
						}
					}
				});
			}
		};
		
		add(cheeses);
		add(new PagingNavigator("navigator", cheeses));
		
		cartContainer = new WebMarkupContainer("cartContainer");
		
		shoppingCart = new ShoppingCartPanel("shoppingCart", getCart());
		cartContainer.add(shoppingCart);
	
		checkout = new Link("checkout") {
			public void onClick() {
				setResponsePage(new CheckOut());
			}
			
			public boolean isVisible() {
				return !getCart().getCheeses().isEmpty();
			}
		};
		cartContainer.add(checkout);

		add(cartContainer.setOutputMarkupId(true));
	}
}
